import axios from 'axios'
import qs from 'qs'
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '../store'
import {
  getToken, whiteList
} from '@/utils/auth'
import {
  filterData
} from '@/utils/index'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  // baseURL:'http://10.180.3.127:9999',
  timeout: 30000 // 请求超时时间
  // headers: {
  //   "Content-Type": "application/x-www-form-urlencoded"
  // },
})

const errorMsgDefault = '系统维护，请联系管理员!'
// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  const sessionJwt = getToken()
  const storeJwt = store.getters.token

  if (sessionJwt && storeJwt && sessionJwt != storeJwt && !whiteList.includes(config.url)) {
    router.push('/')
    location.reload()
  }

  filterData(config.data)
  if (config.method === 'get') {
    // 如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
    config.paramsSerializer = function(params) {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  }
  // if (config.method === 'post') {
  //   config.data = qs.stringify(config.data)
  // }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code === 1) {
      Message({
        message: res.msg || '请求失败!',
        type: 'error',
        duration: 3 * 1000
      })
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('error')
    }
    return res
  }, error => {
    if (error.code === 'ECONNABORTED') {
      Message({
        message: '请求超时!' || error.message,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(error)
    }

    if (error.response.status === 504) {
      Message({
        message: '请求路由跳转超时!' || error.response.statusText,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(error)
    }

    if (error.response.status === 401) {
      Message({
        message: '用户登录超时，请重新登录!' || error.response.statusText,
        type: 'error',
        duration: 3 * 1000
      })

      // let loginForm = store.getters.loginForm;
      // if (loginForm != null && loginForm.username != null && loginForm.password != null) {
      //   // let routePath = '/service/index';
      //   store.dispatch('Login', loginForm).then(res => {
      //     // router.push({ path: routePath });
      //   });
      // }

      store.dispatch('FedLogOut').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })

      return Promise.reject(error)
    }
    if (error.response.status === 500) {
      Message({
        message: error.response.data.errorMsg || errorMsgDefault,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(error)
    }
    if (error.response.status === 400) {
      let checkType = 'warning'
      if (error.response.data.errorMsg == null || error.response.data.errorMsg === '') {
        checkType = 'error'
      }
      Message({
        message: error.response.data.errorMsg || errorMsgDefault,
        type: checkType,
        showClose: true,
        duration: 3 * 1000
      })
      return Promise.reject(error)
    }
    Message({
      message: errorMsgDefault || error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
